{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-12-09T14:36:08.378129Z",
     "start_time": "2024-12-09T14:36:05.475914Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "from torch.utils import data\n",
    "from d2l import torch as d2l\n",
    "\n",
    "true_w = torch.tensor([2, -3.4])\n",
    "true_b = 4.2\n",
    "features,labels = d2l.synthetic_data(true_w, true_b, 100)"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-09T14:36:08.408968Z",
     "start_time": "2024-12-09T14:36:08.391985Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 取数据\n",
    "def load_array(data_arrays, batch_size, is_train=True):\n",
    "    dataset = data.TensorDataset(*data_arrays)\n",
    "    return data.DataLoader(dataset, batch_size, shuffle=is_train)\n",
    "\n",
    "dataloader = load_array((features,labels), 10, is_train=True)\n",
    "next(iter(dataloader))"
   ],
   "id": "913e865c3423933d",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[tensor([[-1.2074, -1.0530],\n",
       "         [-0.3716, -1.8804],\n",
       "         [ 1.4600,  0.4747],\n",
       "         [-0.9647,  0.3696],\n",
       "         [ 0.9676, -1.5874],\n",
       "         [-1.3653,  0.0931],\n",
       "         [ 0.8954,  0.3151],\n",
       "         [ 0.3487, -0.7653],\n",
       "         [-0.1902,  1.2601],\n",
       "         [-0.2897,  0.3238]]),\n",
       " tensor([[ 5.3496],\n",
       "         [ 9.8629],\n",
       "         [ 5.5000],\n",
       "         [ 1.0129],\n",
       "         [11.5206],\n",
       "         [ 1.1523],\n",
       "         [ 4.9087],\n",
       "         [ 7.4970],\n",
       "         [-0.4607],\n",
       "         [ 2.5262]])]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-09T14:36:08.595534Z",
     "start_time": "2024-12-09T14:36:08.581508Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 定义模型\n",
    "from torch import nn\n",
    "\n",
    "net = nn.Sequential(nn.Linear(2, 1))"
   ],
   "id": "853703a78917da9b",
   "outputs": [],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-09T14:36:08.627412Z",
     "start_time": "2024-12-09T14:36:08.614390Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 初始化参数\n",
    "net[0].weight.data.normal_(mean=0, std=0.01)\n",
    "net[0].bias.data.fill_(0)"
   ],
   "id": "7faad037d8ff723",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0.])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-09T14:36:08.719239Z",
     "start_time": "2024-12-09T14:36:08.704350Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 损失函数\n",
    "loss = nn.MSELoss()\n"
   ],
   "id": "65b731f8ff088a0c",
   "outputs": [],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-09T14:36:08.750383Z",
     "start_time": "2024-12-09T14:36:08.737153Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 优化算法\n",
    "trainer = torch.optim.SGD(net.parameters(), lr=0.1)"
   ],
   "id": "82f7ae6626d7edda",
   "outputs": [],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-09T14:36:10.271344Z",
     "start_time": "2024-12-09T14:36:10.223763Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 训练\n",
    "num_epochs = 5\n",
    "for epoch in range(num_epochs):\n",
    "    for X,y in dataloader:\n",
    "        l = loss(net(X), y)\n",
    "        trainer.zero_grad()\n",
    "        l.backward()\n",
    "        trainer.step()\n",
    "    epoch_loss = loss(net(features), labels)\n",
    "    print(f'epoch {epoch + 1}, loss {epoch_loss:f}')\n"
   ],
   "id": "f1720a0ebf44a13e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.552630\n",
      "epoch 2, loss 0.013042\n",
      "epoch 3, loss 0.000460\n",
      "epoch 4, loss 0.000104\n",
      "epoch 5, loss 0.000093\n"
     ]
    }
   ],
   "execution_count": 7
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
